package com.dgz.springboot2302.controller;

import com.dgz.springboot2302.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author duguozheng
 * @Date 2023/03/17  10:12
 * @Description 用于处理与用户相关的操作
 */
@Controller
public class UserController {

    private static File userDir;

    static {
        userDir = new File("./users");
        if (!userDir.exists()) {
            userDir.mkdirs();
        }
    }

    @RequestMapping("/regUser")
    public void register(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("开始处理用户注册！！！！！！！！！！！");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String nickname = request.getParameter("nickname");
        String ageStr = request.getParameter("age");
        System.out.println("表单信息：\n" + "username:" + username + "  password:" + password + "  nickname:" + nickname + "  ageStr:" + ageStr);
        //对浏览器提交的数据进行必要的验证
        if (username == null || username.isEmpty() ||
                password == null || password.isEmpty() ||
                nickname == null || nickname.isEmpty() ||
                ageStr == null || ageStr.isEmpty() ||
                !ageStr.matches("[0-9]+")) {
            try {
                response.sendRedirect("/reg_info_error.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
            //验证通过后，就要将该用户信息保存在服务端
            /*
                将用户提交的注册信息以User实例形式表示，
                然后将该User实例序列化到文件中做长久保存
             */
        }
        int age = Integer.parseInt(ageStr);
        User user = new User(username, password, nickname, age);
        File file = new File(userDir, username + ".obj");

        if (file.exists()) {
            try {
                response.sendRedirect("/have_user.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }

        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))) {//这种try--catch写法可以自动关流
            oos.writeObject(user);
            response.sendRedirect("/reg_success.html");//注册成功后跳转指定页面
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @RequestMapping("/loginUser")
    public void login(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("开始用户登录操作！！！！！！！！");
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        if (username == null || username.isEmpty() ||
                password == null || password.isEmpty()) {
            try {
                response.sendRedirect("/login_info_error.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }

        File file = new File(userDir, username + ".obj");
        if (!file.exists()) {
            try {
                response.sendRedirect("/no_user.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }

        try (
                FileInputStream fis = new FileInputStream(file);
                ObjectInputStream ois = new ObjectInputStream(fis)
        ) {
            User o = (User) ois.readObject();
            if (!o.getPassword().equals(password)) {
                response.sendRedirect("/login_fail.html");
                return;
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        try {
            response.sendRedirect("/login_success.html");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 返回并显示用户列表的方法
     *
     * @param request  请求
     * @param response 响应
     */
    @RequestMapping("/userList")
    public void userList(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("开始处理显示用户列表");
        List<User> userList = new ArrayList<>();//创建集合来保存users目录下所有用户信息

        //获取users目录下所有.obj文件
        File[] files = userDir.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                return pathname.getName().endsWith(".obj");
            }
        });

        //遍历file数组中每一个obj文件，反序列化并存入userList集合
        if (files != null) {
            for (File f : files) {
                try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f))) {
                    User user = (User) ois.readObject();
                    userList.add(user);
                } catch (IOException | ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
        try {
            response.setContentType("text/html;charset=utf-8");
            PrintWriter pw = response.getWriter();

            //写页面
            pw.println("<!DOCTYPE html>");
            pw.println("<html lang=\"en\">");
            pw.println("<head>");
            pw.println("<meta charset=\"UTF-8\">");
            pw.println("<title>用户列表</title>");
            pw.println("</head>");
            pw.println("<body>");
            pw.println("<center>");
            pw.println("<h1>用户列表</h1>");
            pw.println("<table border='3'>");

            pw.println("<tr>");
            pw.println("<td>用户名</td>");
            pw.println("<td>密码</td>");
            pw.println("<td>昵称</td>");
            pw.println("<td>年龄</td>");
            pw.println("</tr>");

            for (User user : userList) {
                pw.println("<tr>");
                pw.println("<td>" + user.getUsername() + "</td>");
                pw.println("<td>" + user.getPassword() + "</td>");
                pw.println("<td>" + user.getNickname() + "</td>");
                pw.println("<td>" + user.getAge() + "</td>");
                pw.println("</tr>");
            }

            pw.println("</table>");
            pw.println("<h2><a href=\"/index.html\">返回首页</a></h2>");
            pw.println("</center>");
            pw.println("</body>");
            pw.println("</html>");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
